#!/bin/bash

# 设置变量
REGISTRY="1.94.151.57:85"
NAMESPACE="fault-inject"
BACKEND_IMAGE_NAME="kube-relayer-backend"
FRONTEND_IMAGE_NAME="kube-relayer-frontend"
TAG="latest"
BACKEND_FULL_IMAGE_NAME="${REGISTRY}/${NAMESPACE}/${BACKEND_IMAGE_NAME}:${TAG}"
FRONTEND_FULL_IMAGE_NAME="${REGISTRY}/${NAMESPACE}/${FRONTEND_IMAGE_NAME}:${TAG}"

# 显示构建信息
echo "===== 构建并推送镜像 ====="
echo "后端镜像: ${BACKEND_FULL_IMAGE_NAME}"
echo "前端镜像: ${FRONTEND_FULL_IMAGE_NAME}"

# 构建后端镜像
echo -e "\n===== 构建后端镜像 ====="
cd backend
docker build -t ${BACKEND_FULL_IMAGE_NAME} .
if [ $? -ne 0 ]; then
    echo "构建后端镜像失败"
    exit 1
fi
echo "构建后端镜像成功: ${BACKEND_FULL_IMAGE_NAME}"

# 推送后端镜像到私有仓库
echo -e "\n===== 推送后端镜像到私有仓库 ====="
docker push ${BACKEND_FULL_IMAGE_NAME}
if [ $? -ne 0 ]; then
    echo "推送后端镜像失败"
    exit 1
fi
echo "推送后端镜像成功: ${BACKEND_FULL_IMAGE_NAME}"

# 返回到项目根目录
cd ..

# 检查前端目录是否存在
if [ -d "frontend" ]; then
    # 构建前端镜像
    echo -e "\n===== 构建前端镜像 ====="
    cd frontend
    docker build -t ${FRONTEND_FULL_IMAGE_NAME} .
    if [ $? -ne 0 ]; then
        echo "构建前端镜像失败"
        exit 1
    fi
    echo "构建前端镜像成功: ${FRONTEND_FULL_IMAGE_NAME}"

    # 推送前端镜像到私有仓库
    echo -e "\n===== 推送前端镜像到私有仓库 ====="
    docker push ${FRONTEND_FULL_IMAGE_NAME}
    if [ $? -ne 0 ]; then
        echo "推送前端镜像失败"
        exit 1
    fi
    echo "推送前端镜像成功: ${FRONTEND_FULL_IMAGE_NAME}"

    # 返回到项目根目录
    cd ..
else
    echo -e "\n前端目录不存在，跳过前端镜像构建"
fi

echo -e "\n===== 完成 ====="
echo "镜像已成功构建并推送到私有仓库:"
echo "- 后端: ${BACKEND_FULL_IMAGE_NAME}"
if [ -d "frontend" ]; then
    echo "- 前端: ${FRONTEND_FULL_IMAGE_NAME}"
fi
echo "您可以使用以下命令部署到Kubernetes集群:"
echo "kubectl apply -f k8s/backend.yaml"
if [ -d "frontend" ]; then
    echo "kubectl apply -f k8s/frontend.yaml"
fi
